/**
 * 所有版权归 广西梧州 陈锦韬 所有
 *
 * @Title: DoubleInnerParameter
 * @Package com.rx.core.dbase.mutil
 * @Description: 双表内联
 * @author: 陈锦韬
 * @date: 2021\7\22 0022
 * @version V1.0
 * @Copyright: 2021 陈锦韬  All rights reserved.
 */
package com.rx.core.dbase.mutil.param;

import com.rx.core.anno.RxRelationField;
import com.rx.core.anno.RxRelationInfo;
import com.rx.core.base.RxBaseConstant;
import com.rx.core.base.RxBaseData;
import com.rx.core.base.RxScanner;
import com.rx.core.data.UrlAnalyse;
import com.rx.core.dbase.RxBaseDbMust;
import com.rx.core.dbase.RxMarkDbMust;
import com.rx.core.enm.RX_VALID;
import com.rx.core.iface.RelationQuery;
import com.rx.core.util.EmptyChecker;
import com.rx.core.util.RxContentHolder;
import com.rx.core.util.RxUtil;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author: Administrator
 * @Description: 双表内联
 * @date: 2021\7\22 0022
 */
@Data
@EqualsAndHashCode(callSuper = true)
@Slf4j
public class DoubleCopyInsertParameter extends MutilTableParameter{

    protected StringBuilder valueSql;
    protected StringBuilder eliminateWhere;

    public static DoubleCopyInsertParameter build(RxBaseData rxBaseData){
        return new DoubleCopyInsertParameter(rxBaseData);
    }

    String getFieldValue(String fieldName,RxBaseData rxBaseData){
        if (RxBaseDbMust.BID.equalsIgnoreCase(fieldName)){
            return ((RxBaseDbMust) rxBaseData).getBid();
        }
        try {
            Field field = RxUtil.Reflection.getField(rxBaseData.getClass(),fieldName);
            return (String)RxUtil.Reflection.getFieldValue(rxBaseData,field);
        } catch (NoSuchFieldException e) {

        }
        return "";
    }
    String replace (String valueField,String column,String value){
        return valueField.replace(column.toUpperCase(),"'" +  value + "' AS " + column.toUpperCase());
    }
    String setRelationField(String valueField,RxBaseData rxBaseData){
        eliminateWhere = new StringBuilder();
        for (Map.Entry<String, Field> entry: secondFieldMap.entrySet()) {
            Field field = entry.getValue();
            RxRelationField rxRelationField = field.getAnnotation(RxRelationField.class);
            if (EmptyChecker.isEmpty(rxRelationField)){
                continue;
            }
            String lineFieldName = RxUtil.StringUtil.humpToLine(field.getName());
            RxRelationInfo[] rxRelationInfos = rxRelationField.value();
            for (RxRelationInfo rxRelationInfo : rxRelationInfos) {
                if (mainTable.equalsIgnoreCase(rxRelationInfo.tableName())){
                    valueField = replace(valueField,lineFieldName,getFieldValue(rxRelationInfo.fieldName(),rxBaseData));
                    eliminateWhere.append(" and eliminate.")
                            .append(lineFieldName)
                            .append("='")
                            .append(getFieldValue(rxRelationInfo.fieldName(),rxBaseData))
                            .append("' ");
                }else{
                    eliminateWhere.append(" and eliminate.")
                            .append(lineFieldName)
                            .append("=source.")
                            .append(lineFieldName);
                }
            }
        }
        return valueField;
    }
    DoubleCopyInsertParameter(RxBaseData rxBaseData) {

        needFilter = false;
        this.rxBaseData = rxBaseData;
        mainClass = rxBaseData.getClass();
        UrlAnalyse urlAnalyse = rxBaseData.getUrlAnalyse();
        mainTable = RxScanner.getTableName(urlAnalyse.getForm());
        String table[] = urlAnalyse.getService().split("_");
        secondTable = RxScanner.getTableName(table[0]);

        mainFieldList = RxScanner.getFieldByName(urlAnalyse.getForm());
        secondFieldList = RxScanner.getFieldByName(table[0]);

        if (table.length > 1){
            // 三表查询
            secondClass = RxScanner.getClassByName("double-" + table[0]);
            threeTable = RxScanner.getTableName(table[1]);
            threeClass = RxScanner.getClassByName(table[1]);
            threeFieldList = RxScanner.getFieldByName(table[1]);
        }else{
            secondClass = RxScanner.getClassByName(table[0]);
        }

        selectSql = super.getSql(rxBaseData,"",secondFieldList,secondFieldMap);
        String valueField = selectSql.toString();
        SimpleDateFormat formatter = new SimpleDateFormat(RxBaseConstant.DATE_FORMAT_DATETIME.trim());
        String dateString = formatter.format(new Date()).trim();

        String userBid = RxContentHolder.getContext().getUserInfo().getUserInfo().getBid();
        valueField = valueField.replace(","+RxBaseDbMust.BID.toUpperCase()+",",",UUID() as "+RxBaseDbMust.BID.toUpperCase()+",".trim());
        valueField = replace(valueField,RxMarkDbMust.CREATE_BY_ID,userBid);
        valueField = replace(valueField,RxMarkDbMust.CREATE_DATE,dateString);
        valueField = replace(valueField,RxMarkDbMust.UPDATE_BY_ID,userBid);
        valueField = replace(valueField,RxMarkDbMust.UPDATE_DATE,dateString);
        valueField = setRelationField(valueField,rxBaseData);


        valueSql = new StringBuilder(valueField);
        selectSql.deleteCharAt(selectSql.length() - 1);
        valueSql.deleteCharAt(valueSql.length() - 1);
        RelationQuery relationQuery = (RelationQuery) rxBaseData;
        whereSql = getMainWhere(secondFieldMap,(RxBaseData)relationQuery.obtainRelation(),"");
        whereSql.append(assignCondition(rxBaseData,""));
    }

    public String getSql(){
        //group_bid='8137debf9c4e4e22aeee949435f8e5f2' and a.item_bid=ITEM_BID
        String sql = "INSERT INTO %s (%s) SELECT %s from %s source where %s AND NOT EXISTS (SELECT eliminate.bid from %s eliminate where eliminate.valid='%s' %s)";
        return String.format(sql, secondTable ,selectSql,valueSql,secondTable,whereSql,secondTable, RX_VALID.NORMAL.getCode(),eliminateWhere);
    }
}
